/*
 * @brief kcp会话
 * @auther aolei1024@gmail.com
 * @date 2019-08-27
 */
#ifndef _KCPCONNECT_H_
#define _KCPCONNECT_H_

#include "UdpConnect.h"
#include "ikcp.h"

#include <memory>
#include <sys/time.h>
#include <mutex>
class KcpConnect
{
    public:
        KcpConnect(std::shared_ptr<UdpConnect> conn_,uint32_t id);
        ~KcpConnect();
        
        //TODO:后面加
        void SendUdp(const char* buf,int len);
        void Send(char* buf,int len); 
        int Recv(char* buf,int len);

        void UpdateSessid(u_int32_t id)
        { 
            std::lock_guard<std::mutex> lk(lock);
            connect = true;
            sessid = id;
            kcp->conv = id;
        }
        uint32_t GetSeeeid()
        {
            return sessid;
        }
        bool GetConnectStatue()
        {
            std::lock_guard<std::mutex> lk(lock);
            return connect;
        }
        
        void Update();
        void Close();
        void Connect();
        void ConnectSuccess();
        void SendSessionStatue(int type);

        /* get system time */
        static inline void itimeofday(long *sec, long *usec)
        {
            struct timeval time;
            gettimeofday(&time, NULL);
            if (sec) *sec = time.tv_sec;
            if (usec) *usec = time.tv_usec;
        }


        static inline IINT64 iclock64(void)
        {
            long s, u;
            IINT64 value;
            itimeofday(&s, &u);
            value = ((IINT64)s) * 1000 + (u / 1000);
            return value;
        }

        static inline IUINT32 iclock()
        {
            return (IUINT32)(iclock64() & 0xfffffffful);
        }
    private:
        std::shared_ptr<UdpConnect> conn = nullptr;
        uint32_t sessid = 0;    //会话ID
        ikcpcb* kcp = nullptr;
        std::mutex lock;
        bool connect = false;
};


#endif //_KCPCONNECT_H_
